﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Newtonsoft.Json.Linq;

namespace test
{
    public class WebUtils
    {
        public static String request(String data, String url)
        {
            Console.WriteLine("input:\n" + data);
            string result = "";
            var map = new Dictionary<string, string>();
            map.Add("value", data);
            map.Add("encode", "base64");
            var mfdc = new System.Net.Http.FormUrlEncodedContent(map);
            mfdc.Headers.Add("platform", "CSharp");
            var clientTask = new System.Net.Http.HttpClient().PostAsync(url, mfdc); //发起异步请求
            clientTask.Wait(); //等待请求结果
            var resultTask = clientTask.Result.Content.ReadAsStringAsync(); //异步读取返回内容
            resultTask.Wait(); //等读取返回内容
            result = resultTask.Result; //返回内容字符串
            Console.WriteLine("output:\n" + result);
            JObject jo = JObject.Parse(result);
            if (jo.GetValue("code").ToString().Equals("0"))
            {
                String base64Str = jo["data"].Value<String>("value");
                Console.WriteLine(base64Str);
                byte[] bytes = Convert.FromBase64String(base64Str);
                try
                {
                    return Encoding.GetEncoding("utf-8").GetString(bytes);
                }
                catch (Exception e)
                {
                    return e.Message;
                }
            }
            else
            {
                return result;
            }
        }
    }
}